/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commands;

import java.util.logging.Level;
import java.util.logging.Logger;
import servidorped.ConversationListFactory;
import servidorped.User;

/**
 *
 * @author Micosil
 */
public class join implements Command {

    @Override
    public boolean execute(String[] stringlist, User user) {
        if (user.getConversationID() != null)
            ConversationListFactory.getList().leaveConversation(user);
        Integer conversationToJoin;
        try{
        conversationToJoin = Integer.parseInt(stringlist[1]);
        }catch(NumberFormatException ex){
            user.getUserSender().setToSend("That is not a valid conversation ID.");            
            return false;
        }
        boolean isAccepted = ConversationListFactory.getList().addUserIfInvited(user, conversationToJoin);
        if (isAccepted){
            user.getUserSender().setToSend("Welcome to conversation " + conversationToJoin);
            Logger.getGlobal().log(Level.INFO, "User {0} has joined conversation {1}", new Object[]{user.getUserName(), conversationToJoin});
            return true;
        }
        user.getUserSender().setToSend("You have not been invited to this conversation.");
        Logger.getGlobal().log(Level.INFO, "User {0} has been denied joining conversation {1}", new Object[]{user.getUserName(), conversationToJoin});
        return true;     
    }
    
}
